import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    Slider,
    TextInput,
    TouchableOpacity,
    DeviceEventEmitter,
    Alert
} from 'react-native';

import { AudioRecorder, AudioUtils } from 'react-native-audio'
import Sound from 'react-native-sound'

import Constant from '../Constant/Constant'
import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import ToastUtils from '../Utils/ToastUtils'
import HttpUtils from '../Utils/HttpUtils'
import RuleUtils from '../Utils/RuleUtils'
import EncryptUtils from '../Utils/EncryptUtils'
import RouterUtils from '../Utils/RouterUtils'
import StorageUtils from '../Utils/StorageUtils'
import TimeUtils from '../Utils/TimeUtils'

//如果是网络音频，使用 new Sound(mp3,null,error => {})
let whoosh = new Sound('http://www.sasz.cn/a.mp3',null,error => {})


export default class PageTest extends React.Component
{
    static navigationOptions = ({navigation}) => ({
        gesturesEnabled: false,//是否支持滑动返回收拾，iOS默认支持，安卓默认关闭
        headerTitle: '测试页面',
        headerStyle: {
            backgroundColor: ColorUtils.blue,
            height: ScreenUtils.statusBarHeight,
        },
        headerRight: (<Text></Text>),
        headerTintColor: ColorUtils.white,
        headerTitleStyle: {
            fontSize: ScreenUtils.Font_18,
            color: ColorUtils.white,
            fontWeight: 'normal',
            flex: 1,
            alignSelf: 'center',
            textAlign: 'center',
        }
    });

    constructor(props)
    {
        super(props);
        this.state = {
            hasPermission: undefined, //授权状态
            audioPath: AudioUtils.DocumentDirectoryPath + '/test.aac', // 文件路径
            recording: false, //是否录音
            pause: false, //录音是否暂停
            stop: false, //录音是否停止
            currentTime: 0, //录音时长

            volume: 0.5,
            seconds: 0, //秒数
            totalMin: '', //总分钟
            totalSec: '', //总分钟秒数
            nowMin: 0, //当前分钟
            nowSec: 0, //当前秒钟
            maximumValue: 0, //滑块最大值
        };
    }

    componentDidMount(){
        let totalTime = whoosh.getDuration();
        totalTime = Math.ceil(totalTime);
        let totalMin = parseInt(totalTime/60); //总分钟数
        let totalSec = totalTime - totalMin * 60; //秒钟数并判断前缀是否 + '0'
        totalSec = totalSec > 9 ? totalSec : '0' + totalSec;
        this.setState({
            totalMin,
            totalSec,
            maximumValue: totalTime,
        })
    }
    componentWillUnmount(){
        this.time && clearTimeout(this.time);
    }
    // 声音+
    _addVolume = () => {
        let volume = this.state.volume;
        volume += 0.1;
        volume = parseFloat(volume).toFixed(1) * 1;
        if(volume > 1){
            return alert('目前已经是最大音量');
        }
        this.setState({volume: volume});
        whoosh.setVolume(volume);
    }
    // 声音-
    _reduceVolume = () => {
        let volume = this.state.volume;
        volume -= 0.1;
        volume = parseFloat(volume).toFixed(1) * 1;
        if(volume < 0){
            return alert('当前为静音');
        }
        this.setState({volume: volume});
        whoosh.setVolume(volume);
    }
    // 播放
    _play = () => {
        whoosh.play();
        this.time = setInterval(() => {
            whoosh.getCurrentTime(seconds => {
                seconds = Math.ceil(seconds);
                this._getNowTime(seconds)
            })
        },1000)
    }
    // 暂停
    _pause = () => {
        clearInterval(this.time);
        whoosh.pause();
    }
    // 停止
    _stop = () => {
        clearInterval(this.time);
        this.setState({
            nowMin: 0,
            nowSec: 0,
            seconds: 0,
        })
        whoosh.stop();
    }
    _getNowTime = (seconds) => {
        let nowMin = this.state.nowMin,
            nowSec = this.state.nowSec;
        if(seconds >= 60){
            nowMin = parseInt(seconds/60); //当前分钟数
            nowSec = seconds - nowMin * 60;
            nowSec = nowSec < 10 ? '0' + nowSec : nowSec;
        }else{
            nowSec = seconds < 10 ? '0' + seconds : seconds;
        }
        this.setState({
            nowMin,
            nowSec,
            seconds
        })
    }
    render() {
        let time = this.state;
        return (
            <View style={styles.container}>
                <Slider
                    // disabled //禁止滑动
                    maximumTrackTintColor={'#ccc'} //右侧轨道的颜色
                    minimumTrackTintColor={'skyblue'} //左侧轨道的颜色
                    maximumValue={this.state.maximumValue} //滑块最大值
                    minimumValue={0} //滑块最小值
                    value={this.state.seconds}
                    onSlidingComplete={(value)=>{ //用户完成更改值时调用的回调（例如，当滑块被释放时）
                        value = parseInt(value);
                        this._getNowTime(value)
                        // 设置播放时间
                        whoosh.setCurrentTime(value);
                    }}
                />
                <Text>{time.nowMin}:{time.nowSec}/{time.totalMin}:{time.totalSec}</Text>
                <Text>当前音量: {this.state.volume}</Text>
                <Text onPress={this._addVolume}>声音+</Text>
                <Text onPress={this._reduceVolume}>声音-</Text>
                <Text onPress={this._play}>播放</Text>
                <Text onPress={this._pause}>暂停</Text>
                <Text onPress={this._stop}>停止</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
});


